import { sendMsgToBackground } from "@/utils/chrome";
import { Message } from "element-ui";
import html2canvas from "html2canvas";
import ScreenShot from "js-web-screen-shot";
import { initGetDocument } from "./getPagesSource";
import { saveToBlueberryApi, screenShot } from "./utils";
import jQuery from 'jquery';

import {
  getDefaultImageFormatStyle
} from "@/logics/shortcutkey";
// 保存网址
export const saveUrl = async () => {
  console.log("保存网址");
  // 获取页面地址
  let href = window.location.href;
  let metaTitleNode = document.querySelector("meta[name='description']")
  let params = {
    href,
    assetName: document.getElementsByTagName('title')[0].innerHTML,
    metaTitle: metaTitleNode ? metaTitleNode.content : ''
  };
  // sendMsgToBackground({ action: "saveUrl", data: params }, callBack);
  sendMsgToBackground(
    { action: "saveUrl", data: params },
    ({ _success, _msg }) => {
      if (!_success) {
        console.error(_msg);
        Message.error({
          customClass: 'el-message-index',
          message:_msg || "操作失败"});
        return;
      }
      Message.success({
        customClass: 'el-message-index',
        message:"操作成功"});
    }
  );
  // sendMsgToBackground({ action: "content-saveUrl", data: "params" });

  // 使用chrome提供截图可视区域的方式获取缩略图
};

// 批量采集
export const batchSave = () => {
  console.log("开始批量采集");
  let images = initGetDocument();
  console.log("images", images)
  return images
  //开启选择区域
};

// 选择区域截图
export const captureArea = () => {
  console.log('测试选择区域截图')
  // 截图确认按钮回调函数
  const callback = ({ base64, cutInfo }) => {
    saveToBlueberryApi({ base64 });
  };
  // 截图取消时的回调函数
  const closeFn = () => {
    console.log("截图窗口关闭");
  };
  new ScreenShot({
    enableWebRtc: true,
    loadCrossImg: true, // 跨域
    level: 40001,
    completeCallback: callback,
    closeCallback: closeFn
  });
};

// 可视力区域截图
export const captureVisible = () => {
  console.log("可视力区域截图，利用chrome api 截图当前tab区域");
  sendMsgToBackground(
    { action: "content-capture-visible-shortcut-api" },
    ({ _success, _msg }) => {
      if (!_success) {
        Message.error({
          customClass: 'el-message-index',
          message:_msg || "操作失败"});
        return;
      }
      Message.success({
        customClass: 'el-message-index',
        message:"操作成功"});
    }
  );
};

// 整页截图
export const captureEntire = async () => {
  try {
    console.log("根据dom获取整个页面截图")
    getCurrentPageFullImage()
    return
    let formatStyle = 'image/' + (await getDefaultImageFormatStyle())
    const canvas = await html2canvas(document.body,{
      useCORS: true,
      foreignObjectRendering: true,
      allowTaint: true
    });
    let base64 = canvas.toDataURL(formatStyle);
    saveToBlueberryApi({ base64 });
    console.log("获取整页面区域截图");
    console.log(base64);
  } catch (e) {
    console.error(e);
  }
};

// 根据dom获取整个页面截图
export const generateDomGetBase64Img = async () => {
  try {
    console.log("根据dom获取整个页面截图")
    getCurrentPageFullImage()
    return
    let formatStyle = 'image/' + (await getDefaultImageFormatStyle())
    const canvas = await html2canvas(document.body);
    let base64 = canvas.toDataURL(formatStyle);
    saveToBlueberryApi({ base64 });
    console.log(base64);
    return base64;
  } catch (e) {
    console.error(e);
  }
};

// 批量采集单个保存接口
export const collectionImageApi = async (base64 ,callBack) => {
    try{
      saveToBlueberryApi({ base64 } ,callBack);
      return base64
    }catch(e){
      console.log(e)
    }

};


/**
 * 获取当前文档所有的全屏截图数据
 */
export async function getCurrentPageFullImage(){
  //获取当前屏幕宽度
  let innerWidth = window.innerWidth 
  //获取当前屏幕高度
  let innerHeight = window.innerHeight 
  //获取当前页面总高度
  let scrollHeight = document.documentElement.scrollHeight
  
  // 判断需要截屏多少次
  let screenshotTimes = 0
  let shortHeight = 0
  let screenHeightArrs = []
  if((scrollHeight % innerHeight) == 0){
    screenshotTimes = scrollHeight / innerHeight
  }else{
    screenshotTimes = Math.ceil(scrollHeight / innerHeight)
    shortHeight = scrollHeight % innerHeight
  }

  for(let i = 0; i < screenshotTimes; i++){
    screenHeightArrs.push({
      w: innerWidth,
      h: innerHeight
    })
  }
  if(shortHeight !== 0){
    screenHeightArrs.push({
      w: innerWidth,
      h: shortHeight
    })

    screenshotTimes += 1
  }

  //开始分页去进行截屏
  let currentPage = 1
  let baseUrls = []
  let scrollTop = 0
  let flag = false
  let classLists = []

  const callBack = async function(base64) {
    let needDealElement = getFloatingElements()
    console.log("needDealElement",needDealElement)
    needDealElement.forEach((ele) => {
      ele.style.display = 'none'
    })
    classLists = [...classLists, needDealElement]
    let tempObj = {
        key: currentPage,
        base64: base64,
        scrollTop,
        w: innerWidth,
        h: innerHeight,
        top: 0
    }
    baseUrls.push(tempObj)


    if(scrollHeight - (scrollTop + innerHeight) > innerHeight ){
      tempObj.w = innerWidth
      tempObj.h = innerHeight
      tempObj.top = 120
      scrollTop = scrollTop + innerHeight

      window.scrollTo(0, scrollTop);
      console.log("处理", scrollTop)
      screenShot({}, callBack)
      return
    }else if(!flag && scrollHeight - (scrollTop + innerHeight) <= innerHeight ){
      let realHeight= scrollHeight - (scrollTop + innerHeight)
      tempObj.w = innerWidth
      tempObj.h = realHeight
      scrollTop = scrollHeight - innerHeight
      tempObj.top = 0

      window.scrollTo(0, scrollTop);
      flag = true
      screenShot({}, callBack)
      return
    }


    console.log('已经获取所有截图数据')
    console.log(baseUrls)
    const canvas =  document.createElement('canvas')
    canvas.width = innerWidth
    canvas.height = scrollHeight
    const ctx = canvas.getContext('2d')
    for(let i = 0; i < baseUrls.length; i++){
      let item = baseUrls[i]
      let img = await asyncImg(item.base64)
      ctx.drawImage( img,0, item.scrollTop, item.w, item.h )
    }


    let formatStyle = 'image/' + (await getDefaultImageFormatStyle())
    let totalBase64 = canvas.toDataURL(formatStyle);
    saveToBlueberryApi({ base64: totalBase64 });

  }

  window.scrollTo(0, 0);
  console.log("处理第", scrollTop)
  // 去截图数据
  screenShot({}, callBack)
}

function asyncImg (base64) {
  return new Promise((resolve) =>{
    let img = new Image()
    img.src = base64
    img.onload = function() {
      resolve(this)
    }
  })
}
function getFloatingElements () {

  var all = document.getElementsByTagName("*");

  // 获取所有浮动元件
  var floatingElements = [];
  for (var i = 0; i < all.length; i++) {
      var elem = all[i];
      var style = getComputedStyle(elem);
      var position = style["position"];
      var isVisible = style.width !== "0" &&
                      style.height !== "0" &&
                      style.opacity !== "0" &&
                      style.display!=='none' &&
                      style.visibility!== 'hidden';
      if ( isVisible && (position.includes("fixed") || position.includes("sticky")) ) {
          floatingElements.push(elem)
      }
  }

  // 取出可疑者
  var annoyingElements = [];
  floatingElements.forEach(function (elem) {
      var $elem = jQuery(elem);
      var windowArea = window.innerHeight * window.innerWidth;
      if (isElementInViewport(elem) && $elem.is(":visible")) {
          var style = getComputedStyle(elem);
          if (
              (
                  $elem.height() * $elem.width() < windowArea * 0.2 && 
                  ($elem.position().top > 10 && $elem.width() < window.innerWidth * 0.8 )
              )
              ||
              (
                  style.bottom === "0px" && style.top !== "0px"
              )
              ||
              (
                  $elem.height() < 100 && $elem.width() < 100 && $elem.height() * $elem.width() < 5625
              )
          ) {
              annoyingElements.push(elem);
          }
      }
  });

  function isElementInViewport(el) {
      if (!el) return false;
      //special bonus for those using jQuery
      if (typeof jQuery === "function" && el instanceof jQuery) {
          el = el[0];
      }
      if (!el) {
          return false;
      }
      var rect = el.getBoundingClientRect();
      if(rect.zIndex > 500){
        return true
      }
      return (
          rect.top + rect.height >= 0 &&
          rect.left >= 0 &&
          rect.bottom - rect.height <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
          rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
      );
  }

  return annoyingElements;

}